/**
 *
 * History:
 *   2010-6-28 0:34:52 Created by ZGong
 */
package gz.gae.blog.file;

import gz.gae.blog.FileDataManager;
import gz.gae.blog.entity.FileData;
import gz.gae.blog.ioc.WebBlogUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by ZGong.
 *
 * @version 1.0 2010-6-28 0:34:52
 */
public class FileDownload
        extends HttpServlet {
    static SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long fId = Long.parseLong(request.getParameter("fId"));
        FileDataManager fdm = WebBlogUtil.getFileDataManager();
        FileData data = fdm.get(fId);
        byte[] buffer = data.getData();
        fdm.close();
        String s = request.getHeader("If-Modified-Since");
        try {
            if (s != null) {
                Date old = df.parse(s);
                if (old.getTime() + 1000 - data.getCreateDate().getTime() >= 0) {
                    response.setStatus(304);
                    return;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        response.setContentType(data.getContentType());
        response.setContentLength((int) data.getSize());
        response.setHeader("Last-Modified", data.getCreateDate().toString());
        response.getOutputStream().write(buffer);
    }
}
